<script setup lang="ts">
import { ref, onMounted,reactive, UnwrapRef, computed } from 'vue'
import { teachHomeworkSub, teachHomeworkCorrect } from '../../stores/api/homework'
import { useCounterStore } from '../../stores/counter'
import { useRoute, useRouter } from "vue-router";
import type { TableProps, UploadProps } from 'ant-design-vue';
import { ImgUrlPrefix } from '../../utils/config'
import type { Rule } from 'ant-design-vue/es/form';
import { UploadOutlined, LoadingOutlined, PictureOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { upload } from '../../utils/upload' // 引入js
const store = useCounterStore()
const router:any = useRouter()
const route:any = useRoute()
const loading = ref(false)
const isShowAttachment = ref(false)
const attachment = ref([])

const fileList = ref<UploadProps['fileList']>([])
const imgList:any = ref([])
const uploading = ref<boolean>(false);
const ids = ref('')
const isShow = ref(false)
const isShowSee = ref<boolean>(false)
const seeData:any = ref({})
interface FormState2 {
  status: Number | undefined;
  feedback: string;
  annex: Array<string>;
  img: Array<string>;
}
const formRef = ref();
const labelCol = { span: 5 };
const wrapperCol = { span: 24 };
const formState2: UnwrapRef<FormState2> = reactive({
  status: undefined,
  feedback: '',
  annex: [], // 附件
  img: [], //图片素材
});
const rules: Record<string, Rule[]> = {
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
});
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',   
    width: 90
  },
  {
    title: '昵称',
    dataIndex: 'nick_name',
    key: 'nick_name'
  },
  {
    title: '学员账号',
    dataIndex: 'mobile',
    key: 'mobile'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '文件',
    dataIndex: 'attachment',
    key: 'attachment',
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
  },
  {
    title: '最近提交时间',
    dataIndex: 'submit_at',
    key: 'submit_at',
  },
  {
    title: '批改时间',
    dataIndex: 'correct_at',
    key: 'correct_at',
  },
  {
    title: '作业内容',
    dataIndex: 'content',
    key: 'content',
  },
//   {
//     title: '反馈意见',
//     dataIndex: 'feedback',
//     key: 'feedback',
//   },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
  },
];
const data_list = ref([])

interface FormState {
  title: string;
  status: string;
  type: string;
}
const formState: UnwrapRef<FormState> = reactive({
  title: '',
  status: '', 
  type: ''
});

// 作业列表
const getCourseList = () => {
    loading.value = true
    teachHomeworkSub({ page:  pagination.current, title: formState.title, status: formState.status, id: Number(route.query.id)}, 'post').then((res: any) => {
        console.log(res)
        if (res.code == 200) {
            data_list.value = res.data.items
            pagination.total = res.data.total
        }
        loading.value = false
    }).catch((err: any) => {
        console.log(err)
        loading.value = false
    })
}

const homeworkList = computed(() => {
  return data_list.value.map(item => {
       return { ...item, attachment: item.attachment ? JSON.parse(item.attachment) : '',created_at: store.timestampChangDate(item.created_at * 1000), deadline: store.timestampChangDate(item.deadline * 1000),submit_at: store.timestampChangDate(item.submit_at * 1000), correct_at: item.correct_at ? store.timestampChangDate(item.correct_at * 1000) : 0, correct_url: item.correct_url ? JSON.parse(item.correct_url) : '' }
  })
})

// 图片地址拼接
const getImgUrl = (val) => {
    const url = ImgUrlPrefix(val)
    return url
}

// 截取字符串
const getExtractString = (val) => {
    if(val) {
        const startIndex = val.lastIndexOf('/') + 1
        const url = val.substring(startIndex);
        return url
    } else{
        return ''
    }
}

// 查看更多
const seeMore = (val) => {
    isShowAttachment.value = true
    attachment.value = val.attachment
}

// 搜索
const onSubmit = () => {
    getCourseList()
}
// 取消
const onCancel = () => {
    formState.title = ''
    formState.status = ''
    formState.type = ''
    getCourseList()
}
const handleTableChange: TableProps['onChange'] = (
  pag: { pageSize: number; current: number }
) => {
  console.log(pag?.current)
  pagination.current = pag?.current
  getCourseList()
};

// 批改作业
const handleCorrect = (val:any) => {
    isShow.value = true
    ids.value = val.id
    formState2.status = val.status
    formState2.feedback = val.feedback
    formState2.annex = [] // 附件
    formState2.img = [] //图片素材
    if(val.correct_url.length > 0 && Array.isArray(val.correct_url[0])) {
        for(let i = 0;i < val.correct_url.length; i++) {
            if(i == 0) {
                formState2.img = val.correct_url[0] || []
                let array2 = val.correct_url[0] || []
                let arrImg = array2.map(item => {
                    return {
                        uid: '-1',
                        name: item.substring(item.lastIndexOf('/') + 1),
                        status: 'done',
                        url: getImgUrl(item),
                    }
                })
                console.log(arrImg,'arrImg')
                imgList.value = arrImg
            }
            if(i == 1) {
                formState2.annex = val.correct_url[1] || [] // 上传附件文件
                let array = val.correct_url[1] || []
                let arr2 = array.map(item => {
                    return { name: item.substring(item.lastIndexOf('/') + 1), status: 'done', url: getImgUrl(item), uid: '' }
                })
                console.log(arr2,'arr2')
                fileList.value = arr2
            }
        }
    } else if(val.correct_url.length > 0 && !Array.isArray(val.correct_url[0])) {
        formState2.annex = val.correct_url
        let array = val.correct_url || []
        let arr2 = array.map(item => {
            return { name: item.substring(item.lastIndexOf('/') + 1), status: 'done', url: getImgUrl(item), uid: '' }
        })
        console.log(arr2,'arr2')
        fileList.value = arr2
    }
}

// 查看
const handleSee = (val:any) => {
    isShowSee.value = true
    seeData.value = {
        ...val,
        correct_url: val.correct_url
    }
}

// 取消
const resetForm = () => {
  formRef.value.resetFields();
  isShow.value = false
  fileList.value = []
};
const onSubmit2 = () => {
    formRef.value
    .validate()
    .then(() => {
      console.log('values', formState);
      correctFun()
    })
    .catch(error => {
      console.log('error', error);
    });
}

// 调用批改作业接口
const correctFun = () => {
    let attachment = [formState2.img, formState2.annex]
    let obj = {
        "id": ids.value,
        "status": formState2.status,
        "feedback": formState2.feedback,
        "correct_url": attachment ? JSON.stringify(attachment) : '',
    }
    console.log(obj)
    teachHomeworkCorrect(obj, 'post').then((res: any) => {
        console.log(res)
        if(res.code == 200) {
            message.success(res.message);
            formRef.value.resetFields();
            isShow.value = false
            formState2.img = []
            imgList.value = []
            formState2.annex = []
            fileList.value = []
            getCourseList()
        } else {
            message.error(res.message);
        }
    }).catch((err: any) => {
        console.log(err)
    })
}

// 上传附件
const beforeUpload: UploadProps['beforeUpload'] = file => {
  const isPNG = file.type === 'image/png';
//   if (!isPNG) {
//     message.error(`${file.name} is not a png file`);
//   }
//   return isPNG || Upload.LIST_IGNORE;
  return true
};
// 附件上传
const handleUpload = (data) => {
    console.log('上传11')
    console.log(data,'handleUpload')
    upload(data.file,res => {
      console.log(res,'ddddd')
      if(res) {
            const startIndex = res.indexOf('/') + 1;
            const urls = res.substring(startIndex);
            formState2.annex = [...formState2.annex, urls]
            fileList.value.forEach(item => {
                if(item.uid == data.file.uid){
                    item.status = 'done'
                }
            })
            console.log(urls, fileList.value)
      } else {
        
      }
    }).catch(err => {
    })
}
// 删除
const handleRemov = (file) => {
  console.log('file',file)
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
  formState2.annex.splice(index,1)
}

// 图片上传--删除
const handleRemoveImg: UploadProps['onRemove'] = file => {
  console.log('file',file)
  const index = imgList.value.indexOf(file);
  const newFileList = imgList.value.slice();
  newFileList.splice(index, 1);
  formState2.img.splice(index, 1)
  imgList.value = newFileList;
};
// 图片上传之前
const beforeUploadImg: UploadProps['beforeUpload'] = file => {
//   imgList.value = [...(imgList.value || []), file];
//   console.log(imgList.value)
  return true;
};
// 图片上传
const handleUploadImg = (data) => {
//   const formData = new FormData();
//   imgList.value.forEach((file: UploadProps['fileList'][number]) => {
//     formData.append('files[]', file as any);
//   });
  uploading.value = true;
  console.log(imgList.value, data,'handleUpload')
  upload(data.file,res => {
      console.log(res,'ddddd')
      if(res) {
            const startIndex = res.indexOf('/') + 1;
            const urls = res.substring(startIndex);
            formState2.img.push(urls)
            imgList.value.push({
                uid: '-1',
                name: urls.substring(urls.lastIndexOf('/') + 1),
                status: 'done',
                url: getImgUrl(urls),
            })
            console.log(urls)
      }
      uploading.value = false;
  })
};

// 下载
const onDownload = (item:any) => {
    let val = getImgUrl(item)
    window.open(val, '_blank');
}
onMounted(() => {
    getCourseList()
    console.log('route.query.p_id',route.query.class_id,route.query.id)
})
</script>

<template>
    <div class="homeworkSubmit">
        <a-page-header
            style="border: none;padding: 0"
            title="作业提交"
            sub-title=""
            @back="() => $router.go(-1)"
        />
        <div class="list-box">
            <div class="form-filter">
                <!-- <a-form layout="inline" :model="formState">
                    <a-form-item label="标题">
                        <a-input v-model:value="formState.title" placeholder="请输入标题" />
                    </a-form-item>
                    <a-form-item label="状态">
                        <a-select v-model:value="formState.status" placeholder="请选择状态" style="width: 130px">
                            <a-select-option :value="10">未提交</a-select-option>
                            <a-select-option :value="20">重新提交</a-select-option>
                            <a-select-option :value="30">已完成</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item>
                        <a-button type="primary" class="btn-ss" @click="onSubmit">搜索</a-button>
                        <a-button style="margin: 0 20px;" @click="onCancel">取 消</a-button>
                    </a-form-item>
                </a-form> -->
            </div>
            <a-table :columns="columns" :pagination="pagination" :scroll="{ x: 1500}"
                :loading="loading" :data-source="homeworkList" @change="handleTableChange">
                <template #bodyCell="{ column, record }">
                    
                    <template v-if="column.key === 'id'">
                        <span>
                        {{ record.id }}
                        </span>
                    </template>
                    <template v-if="column.key === 'nick_name'">
                        <span>
                        {{ record.user && record.user.nick_name ? record.user.nick_name : ''}}
                        </span>
                    </template>
                    <template v-if="column.key === 'mobile'">
                        <span>
                        {{  record.user && record.user.mobile ? record.user.mobile : '' }}
                        </span>
                    </template>
                    <template v-else-if="column.key === 'status'">
                        <span>
                            <a-tag color="green" v-if="record.status == 10">未提交</a-tag>
                            <a-tag color="cyan" v-else-if="record.status == 20">重新提交</a-tag>
                            <a-tag color="blue" v-else-if="record.status == 30">已完成</a-tag>
                            <span v-else>--</span>
                        </span>
                    </template>
                    <template v-else-if="column.key === 'attachment'">
                        <span v-if="record.attachment.length > 1">
                            <a @click="seeMore(record)">查看更多</a>
                        </span>
                        <span v-else>
                            <a :href="getImgUrl(item)" v-for="item in record.attachment" :key="item" rel="noopener noreferrer"> {{  getExtractString(item) }}</a>
                        </span>
                    </template>
                    <template v-if="column.key === 'created_at'">
                        <span>
                        {{ record.created_at || '--' }}
                        </span>
                    </template>
                    <template v-if="column.key === 'submit_at'">
                        <span>
                        {{ record.submit_at || '--' }}
                        </span>
                    </template>
                    <template v-if="column.key === 'correct_at'">
                        <span>
                        {{ record.correct_at || '--' }}
                        </span>
                    </template>
                    <template v-if="column.key === 'content'">
                        <span>
                        {{ record.content || '--' }}
                        </span>
                    </template>
                    <!-- <template v-if="column.key === 'feedback'">
                        <span>
                        {{ record.feedback || '--' }}
                        </span>
                    </template> -->
                    <!-- <template v-if="column.key === 'desc'">
                        <a-tooltip placement="top" v-if="record.desc.length > 40">
                            <template #title>
                                 <span>{{ record.desc }}</span>
                            </template>
                            <span>
                               {{ record.desc }}
                            </span>
                        </a-tooltip>
                        <span v-else>
                            {{ record.desc }}
                        </span>
                    </template> -->
                    <template v-else-if="column.key === 'action'">
                        <span style="margin-right: 10px">
                          <a @click="handleCorrect(record)">批改作业</a>
                        </span>
                        <span style="margin-right: 10px">
                          <a @click="handleSee(record)">查看</a>
                        </span>
                    </template>
                </template>
            </a-table>
        </div>
        <a-modal v-model:open="isShow" title="批改作业" ok-text="" cancel-text="" @cancel="resetForm" :footer="null">
            <div class="live-left">
                <a-form
                    ref="formRef"
                    :model="formState2"
                    :rules="rules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                >
                    <a-form-item label="状态" name="status">
                        <a-select v-model:value="formState2.status" placeholder="请选择状态">
                            <a-select-option :value="20">重新提交</a-select-option>
                            <a-select-option :value="30">已完成</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="图片素材" name="img">
                        <a-upload class="cover-g" name="avatar" accept=".png,.jpg,.webp,.gif,.jpeg,.svg" list-type="picture-card" :file-list="imgList" :before-upload="beforeUploadImg" @remove="handleRemoveImg" :customRequest="handleUploadImg">
                            <div>
                                <loading-outlined v-if="uploading"></loading-outlined>
                                <PictureOutlined v-else :style="{fontSize: '22px'}" />
                                <div class="ant-upload-text">上传图片</div>
                            </div>
                        </a-upload>
                    </a-form-item>
                    <a-form-item name="annex" label="附件">
                        <a-upload
                            v-model:file-list="fileList"
                            :before-upload="beforeUpload"
                            :customRequest="handleUpload"
                            @remove="handleRemov"
                            accept=".doc,.docx,.pdf,.xlsx,.xls"
                        >
                            <a-button>
                                <upload-outlined></upload-outlined>
                                上传附件
                            </a-button>
                        </a-upload>
                    </a-form-item>
                    <a-form-item ref="feedback" label="反馈意见" name="feedback">
                        <a-textarea
                            v-model:value="formState2.feedback"
                            placeholder="请输入反馈意见"
                            :auto-size="{ minRows: 4}"
                        />
                    </a-form-item>
                    <a-form-item :wrapper-col="{ span: 24, offset: 4 }" style="text-align: right;">
                        <a-button class="btn-ss" type="primary" @click="onSubmit2">提交</a-button>
                        <a-button style="margin-left: 10px" @click="resetForm">取消</a-button>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>
        <a-modal v-model:open="isShowAttachment" :title="'文件'" width="700px" ok-text="" cancel-text="" :footer="null">
            <div class="live-left">
                <div v-for="(item, index) in attachment" :key="index" style="display: flex;flex-wrap: wrap;">
                    <div>{{ index == 0 ? '图片素材：': '其他附件：'}}</div>
                    <div>
                        <div v-if="index == 0">
                            <img class="image-material" :src="getImgUrl(m)" alt="" v-for="(m, idx) in item" :key="idx">
                        </div>
                        <!-- <a v-else :href="getImgUrl(m)" target="_blank" v-for="(m, idx) in item" :key="idx" rel="noopener noreferrer"> {{  getExtractString(m) }}</a> -->
                        <div v-else  v-for="(m, idx) in item" :key="idx">
                            <span style="color: #1677ff;margin-right:15px"> {{  getExtractString(m) }}</span>
                            <a-tag color="default" style="cursor: pointer;" @click="onDownload(m)" v-if="m">下载</a-tag>
                        </div>
                    </div>
                </div>
            </div>
        </a-modal>
        <a-modal v-model:open="isShowSee" :title="'详情'" width="900px" ok-text="" cancel-text="" :footer="null">
            <div>
                <!-- <div class="content-box">
                    <div class="name-item">反馈意见：<span class="content-ssv">{{seeData.feedback}}</span></div>
                    <div class="name-item">
                        附件：
                        <div>
                            <div v-for="(item, index) in seeData.correct_url" :key="index">
                                <a :href="getImgUrl(item)" target="_blank" rel="noopener noreferrer"> {{  getExtractString(item) }}</a>
                            </div>
                        </div>
                    </div>
                </div> -->
                <a-descriptions title="" bordered size="small">
                    <a-descriptions-item label="ID">{{seeData.id}}</a-descriptions-item>
                    <a-descriptions-item label="昵称">{{ seeData && seeData.user ? seeData.user.nick_name : '-' }}</a-descriptions-item>
                    <a-descriptions-item label="学员账号">
                        {{ seeData && seeData.user ? seeData.user.mobile : '-' }}
                    </a-descriptions-item>
                    <a-descriptions-item label="状态">
                            <a-tag color="green" v-if="seeData.status == 10">未提交</a-tag>
                            <a-tag color="cyan" v-else-if="seeData.status == 20">重新提交</a-tag>
                            <a-tag color="blue" v-else-if="seeData.status == 30">已完成</a-tag>
                            <span v-else>--</span>
                    </a-descriptions-item>
                    <a-descriptions-item v-if="seeData.attachment.length > 0 && !Array.isArray(seeData.attachment[0])" :label="'其他附件'" v-for="(item, index) in seeData.attachment" :key="index">
                        <div v-for="(item, index) in seeData.attachment" :key="index">
                            <!-- <a :href="getImgUrl(item)" target="_blank" rel="noopener noreferrer"> {{  getExtractString(item) }}</a> -->
                            <span style="color: #1677ff;margin-right:15px"> {{  getExtractString(item) }}</span>
                            <a-tag color="default" style="cursor: pointer;" @click="onDownload(item)">下载</a-tag>
                        </div>
                    </a-descriptions-item>
                    <a-descriptions-item v-if="seeData.attachment.length > 0 && Array.isArray(seeData.attachment[0])" :label="index == 0 ? '图片素材': '其他附件'" v-for="(item, index) in seeData.attachment" :key="index">
                        <div>
                            <div v-if="index == 0">
                                <img class="image-material2" :src="getImgUrl(m)" alt="" v-for="(m, idx) in item" :key="idx">
                            </div>
                            <div v-else  v-for="(m, idx) in item" :key="idx">
                                <span style="color: #1677ff;margin-right:15px"> {{  getExtractString(m) }}</span>
                                <a-tag color="default" style="cursor: pointer;" @click="onDownload(m)" v-if="m">下载</a-tag>
                            </div>
                        </div>
                    </a-descriptions-item>
                    <a-descriptions-item label="创建时间">
                        {{ seeData.created_at}}
                    </a-descriptions-item>
                    <a-descriptions-item label="最近提交时间">
                        {{ seeData.submit_at}}
                    </a-descriptions-item>
                    <a-descriptions-item label="作业内容">
                        {{ seeData.content}}
                    </a-descriptions-item>
                </a-descriptions>
                <div v-if="seeData && seeData.correct_at !== 0">
                    <div class="title-aa">批改作业</div>
                    <a-descriptions title="" bordered size="small">
                        <a-descriptions-item label="批改时间">
                            {{ seeData.correct_at || '-'}}
                        </a-descriptions-item>
                        <a-descriptions-item v-if="seeData.correct_url.length > 0 && !Array.isArray(seeData.correct_url[0])" :label="'其他附件'" v-for="(item, index) in seeData.correct_url" :key="index">
                            <div v-for="(item, index) in seeData.correct_url" :key="index">
                                <!-- <a :href="getImgUrl(item)" target="_blank" rel="noopener noreferrer"> {{  getExtractString(item) }}</a> -->
                                <span style="color: #1677ff;margin-right:15px"> {{  getExtractString(item) }}</span>
                                <a-tag color="default" style="cursor: pointer;" @click="onDownload(item)">下载</a-tag>
                            </div>
                        </a-descriptions-item>
                        <a-descriptions-item v-if="seeData.correct_url.length > 0 && Array.isArray(seeData.correct_url[0])" :label="index == 0 ? '图片素材': '其他附件'" v-for="(item, index) in seeData.correct_url" :key="index">
                            <div>
                                <div v-if="index == 0">
                                    <img class="image-material2" :src="getImgUrl(m)" alt="" v-for="(m, idx) in item" :key="idx">
                                </div>
                                <!-- <a v-else :href="getImgUrl(m)" target="_blank" v-for="(m, idx) in item" :key="idx" rel="noopener noreferrer"> {{  getExtractString(m) }}</a> -->
                                <div v-else  v-for="(m, idx) in item" :key="idx">
                                    <span style="color: #1677ff;margin-right:15px"> {{  getExtractString(m) }}</span>
                                    <a-tag color="default" style="cursor: pointer;" @click="onDownload(m)">下载</a-tag>
                                </div>
                            </div>
                        </a-descriptions-item>
                        <a-descriptions-item label="反馈意见：">
                            <span>
                            {{ seeData.feedback }}
                            </span>
                        </a-descriptions-item>
                    </a-descriptions>
                </div>
            </div>
        </a-modal>
    </div>
</template>

<style scoped>
.homeworkSubmit{
    padding: 15px;
}
.top-content-p{
    background-color: #fff;
    /* padding: 10px 15px;
    border-radius: 6px; */
}
.title-item-p{
    line-height: 40px;
    font-weight: bold;
    font-size: 16px;
}
.content-ssv{
    color: #000;
    margin-left:4px;
}
.btn-ss{
    background-color: #fe5d26;
    height: 32px;
}
.btn-ss:hover{
    background-color: #fe5d26;
}
.btn-sub{
    background-color: #87d068;
    height: 32px;
}
.btn-sub:hover{
    background-color: #87d068;
}
.list-box{
    margin-top: 15px;
}

.form-filter{
   margin: 20px 0;   
   display: flex;
   justify-content: space-between;
}
.thumbnail_{
    width: 80px;
}
.cover-g{
    /* background-color: rgb(51,52,63); */
    width: 100%;
    /* height: 132px; */
    line-height: 26px;
    /* text-align: center; */
    padding: 10px 0;
    border-radius: 10px;
}
.cover-image{
    width: 100%;
    height: 100%;
}
.cover-image img{
    width: 100%;
    height: 100%;
}
.image-material{
    width: 120px;
    height: 120px;
}
.image-material2{
    width: 60px;
    height: 60px;
}

.box-flex{
    display: flex;
    align-items: center;
}
.content-box{
    display: flex;
    flex-wrap: wrap;
    margin: 6px 0;
}
.name-item{
    line-height: 36px;
    min-width: 200px;
    color: #333;
    margin-right: 40px;
    display: flex;
    flex-wrap: wrap;
}
.name-item span{
    margin-left:4px;
}
.title-aa{
    margin: 20px 0;
    font-size: 16px;
    font-weight: bold;
    color: #333;
}
</style>
